package com.wie.controller;

import com.wie.config.RedisConfiguration;
import com.wie.pojo.Result;
import com.wie.pojo.User;
import com.wie.service.UserService;
import com.wie.utils.JwtUtil;
import com.wie.utils.Md5Util;
import com.wie.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Validated
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户注册
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result register( String username,  String password) {
        // 查询用户是否存在
        User user = userService.findByUsername(username);
        if(user != null) {
            return Result.error("用户已存在");
        }
        // 新增用户
        userService.register(username, password);
        log.info("用户注册：{}", username);
        return Result.success();
    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result login(String username, String password) {
        // 根据用户名查询用户
        User loginUser = userService.findByUsername(username);
        // 校验用户是否存在
        if(loginUser == null) {
            return Result.error("用户不存在");
        }
        // 判断密码是否正确
        if(!(Md5Util.getMD5String(password)).equals(loginUser.getPassword())) {
            return Result.error("密码错误");
        }
        log.info("用户登录: {}", username);
        // 校验成功，生成令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("id", loginUser.getId());
        claims.put("username", loginUser.getUsername());
        String token = JwtUtil.genToken(claims);
        // 把token存储至redis中
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set(token, token, 1, TimeUnit.HOURS);
        return Result.success(token);
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/userInfo")
    public Result<User> userInformation(){
        // 根据用户用查询用户
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUsername(username);
        log.info("获取用户信息：{}", user);
        return Result.success(user);
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        log.info("更新用户信息：{}", user);
        userService.update(user);
        return Result.success();
    }

    /**
     * 更新用户头像
     * @param avatarUrl
     * @return
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        log.info("更新用户头像");
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    /**
     * 更新用户密码
     * @param params
     * @return
     */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token) {
        log.info("更新用户密码");
        // 校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(newPwd)) {
            return Result.error("缺少必要参数");
        }
        // 调用service 校验原密码是否正确
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User loginUser = userService.findByUsername(username);
        if (!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("密码错误");
        }
        if(!rePwd.equals(newPwd)) {
            return Result.error("两次密码填写不一致");
        }
        userService.updatePwd(newPwd);
        // 删除redis中对应的token
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }

}
